import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus';
import { staticRoutes } from '@/router/routes';
import { loginApi, getUserInfoApi, logoutApi } from '@/api/acl/user';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
  }),

  actions: {
    /**
     * 登陆
     * @param username
     * @param password
     */
    async login(username: string, password: string) {
      const { token } = await loginApi(username, password);
      this.token = token;
      setToken(token);
    },

    /**
     * 获取用户信息
     */
    async getInfo() {
      const info = await getUserInfoApi();
      this.name = info.name;
      this.avatar = info.avatar;

      this.menuRoutes = staticRoutes;
    },

    /**
     * 重置/退出登陆
     */
    async reset() {
      // 如果当前是登陆的, 请求退出登陆
      if (this.name) {
        await logoutApi();
      }
      // 删除local中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = '';
      this.name = '';
      this.avatar = '';
    },
  },
});
